package 剑指Offer.easy;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class 二叉搜索树的第k大节点 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    class Solution2 {
        public int kthLargest(TreeNode root, int k) {
            List<Integer> res = new ArrayList<>();
            Deque<TreeNode> stack = new LinkedList<>();
            while (root != null || !stack.isEmpty()) {
                while (root != null) {
                    stack.push(root);
                    root = root.left;
                }
                root = stack.pop();
                res.add(root.val);
                root = root.right;
            }
            return res.get(res.size() - k);
        }
    }

    class Solution {
        public int kthLargest(TreeNode root, int k) {
            Deque<TreeNode> stack = new LinkedList<>();
            while (root != null || !stack.isEmpty()) {
                while (root != null) {
                    stack.push(root);
                    root = root.right;
                }
                root = stack.pop();
                if (--k == 0) return root.val;
                root = root.left;
            }
            return -1;
        }
    }
}
